import type { Plugin } from 'vue'
import qs from 'qs'
import { TOKEN_NAME, useAppEnv, useAuthorization } from '@/composables/app'

export interface RequestOptions extends UniApp.RequestOptions {
  ignoreToken?: boolean
  withTimestamp?: boolean
  errorMsg?: boolean
  loading?: boolean
}

const { VITE_API_URL, VITE_API_BASE_URL } = useAppEnv()

const interceptor: UniApp.InterceptorOptions = {
  invoke: (options: RequestOptions) => {
    const { url, timeout = 10000 } = options

    const data = (options.data || {}) as Record<string, any>
    const method = options.method?.toLocaleUpperCase() || 'GET'

    if (options.withTimestamp && method === 'GET') {
      data.timestamp = new Date().getTime()
    }

    if (method.toLocaleUpperCase() === 'GET' && data) {
      options.url = `${url}?${qs.stringify(data)}`
    }

    // 拼接全路径
    if (url.startsWith('http')) {
      // #ifdef H5
      options.url = `${VITE_API_BASE_URL}${url}`
      // #endif

      // #ifndef H5
      options.url = `${VITE_API_URL}${url}`
      // #endif
    }

    // 添加token
    if (!options.ignoreToken) {
      const token = useAuthorization()
      if (token.value) {
        options.header = {
          ...options.header,
          [TOKEN_NAME]: token.value,
        }
      }
    }
    // 超时时间
    options.timeout = timeout
  },
}

export const requestInterceptor: Plugin = {
  install() {
    uni.addInterceptor('request', interceptor)
    uni.addInterceptor('uploadFile', interceptor)
  },
}
